<template>
  <GlobalDrawer
    v-model="visible"
    :title="drawerTitle"
    :size="size"
    :before-close="handleBeforeClose"
    :show-footer-buttons="!isView"
    @confirm="handleConfirm"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="trace-form"
      label-position="top"
    >
      <el-form-item label="跟进内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="请输入跟进内容"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="跟进类型" prop="types">
        <el-select
          v-model="formData.types"
          placeholder="请选择跟进类型"
          :disabled="isView"
          :loading="typesLoading"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in traceTypes"
            :key="item.id"
            :label="item.title || item.name || item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="联系人" prop="contact_id">
        <el-select
          v-model="formData.contact_id"
          placeholder="请选择联系人"
          :disabled="isView"
          :loading="contactLoading"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="item in contactList"
            :key="item.id"
            :label="item.name || item.title || item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="机会线索" prop="chance_id">
        <el-select
          v-model="formData.chance_id"
          placeholder="请选择机会线索（可选）"
          :disabled="isView"
          :loading="chanceLoading"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="item in chanceList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跟进阶段" prop="stage">
        <el-select
          v-model="formData.stage"
          placeholder="请选择跟进阶段（可选）"
          :disabled="isView"
          :loading="stageLoading"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in stageList"
            :key="item.id"
            :label="item.title || item.name || item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跟进时间" prop="follow_time">
        <el-date-picker
          v-model="formData.follow_time"
          type="datetime"
          placeholder="请选择跟进时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :clearable="false"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="下次跟进时间" prop="next_time">
        <el-date-picker
          v-model="formData.next_time"
          type="datetime"
          placeholder="请选择下次跟进时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :clearable="true"
          @clear="handleNextTimeClear"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item v-if="mode === 'view'">
        <div class="trace-info">
          <div class="info-item">
            <span class="label">跟进人：</span>
            <span class="value">{{ formData.admin_name || '未知' }}</span>
          </div>
          <div class="info-item">
            <span class="label">跟进时间：</span>
            <span class="value">
              {{ formData.create_time ? formatDateTime(formData.create_time) : '未知' }}
            </span>
          </div>
          <div class="info-item">
            <span class="label">下次跟进：</span>
            <span class="value">
              {{ formData.next_time ? formatDateTime(formData.next_time) : '无' }}
            </span>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, onMounted } from 'vue'
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
  import { GlobalDrawer } from '@/components/common'
  import { customerApi } from '@/api/customer'
  import request from '@/utils/request'
  import { ApiResponse } from '@/types/api'
  import { formatDate, formatDateTime } from '@/utils/format'
  import { CustomerChance } from '@/types/customer'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    customerId: {
      type: [Number, String],
      required: true,
    },
    traceId: {
      type: [Number, String],
      default: '',
    },
    mode: {
      type: String,
      default: 'add', // 'add', 'edit', 'view'
      validator: (value: string) => ['add', 'edit', 'view'].includes(value),
    },
    size: {
      type: String,
      default: '80%',
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  // 表单引用
  const formRef = ref<FormInstance>()

  // 抽屉可见状态
  const visible = computed({
    get: () => props.modelValue,
    set: val => emit('update:modelValue', val),
  })

  // 提交状态
  const submitting = ref(false)

  // 数据加载状态
  const typesLoading = ref(false)
  const contactLoading = ref(false)
  const chanceLoading = ref(false)
  const stageLoading = ref(false)
  const allDataLoaded = ref(false) // 全局数据加载标志

  // 数据列表
  const traceTypes = ref<any[]>([])
  const contactList = ref<any[]>([])
  const chanceList = ref<CustomerChance[]>([])
  const stageList = ref<any[]>([])

  // 表单数据
  const formData = reactive({
    id: '',
    customer_id: '',
    content: '',
    types: '', // 跟进类型
    contact_id: '', // 联系人ID
    chance_id: '', // 机会线索ID
    stage: '', // 跟进阶段
    follow_time: '',
    next_time: '',
    admin_id: 0,
    admin_name: '',
    create_time: '',
  })

  // 表单验证规则
  const rules = {
    content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
    types: [{ required: true, message: '请选择跟进类型', trigger: 'change' }],
    follow_time: [{ required: true, message: '请选择跟进时间', trigger: 'change' }],
  }

  // 重置表单
  const resetForm = () => {
    if (props.mode === 'add') {
      formData.id = ''
      formData.content = ''
      formData.types = '' // 跟进类型
      formData.contact_id = '' // 联系人ID
      formData.chance_id = '' // 机会线索ID
      formData.stage = '' // 跟进阶段
      // 使用当前时间的格式化字符串作为默认值
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      formData.follow_time = `${year}-${month}-${day} ${hour}:${minute}:${second}`
      formData.next_time = ''
      formData.admin_id = 0
      formData.admin_name = ''
      formData.create_time = ''
    }
  }

  // 加载所有数据列表 - 优化版本
  const loadAllDataLoading = ref(false) // 专门用于防止重复调用的加载状态
  
  const loadAllData = async () => {
    // 全局防重复加载检查 - 多层保护机制
    if (allDataLoaded.value) {
      console.log('数据已经加载过，跳过重复加载')
      return
    }

    // 检查是否已有数据加载进行中 - 更严格的检查
    const isLoading =
      typesLoading.value || contactLoading.value || chanceLoading.value || stageLoading.value
    if (isLoading) {
      console.log('数据正在加载中，跳过重复请求')
      return
    }

    // 添加加载中标志，防止并发调用
    if (loadAllDataLoading.value) {
      console.log('loadAllData正在执行中，跳过重复调用')
      return
    }
    loadAllDataLoading.value = true

    console.log('开始加载所有数据列表...')

    try {
      // 创建超时Promise，防止请求卡死
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('数据加载超时')), 30000) // 30秒超时
      })

      // 并行加载所有数据，但使用Promise.race添加超时保护
      const loadDataPromise = Promise.allSettled([
        loadTraceTypes(),
        loadContactList(),
        loadChanceList(),
        loadStageList(),
      ])

      const results = (await Promise.race([
        loadDataPromise,
        timeoutPromise,
      ])) as PromiseSettledResult<any>[]

      // 检查是否有请求成功
      const successCount = results.filter((result: PromiseSettledResult<any>) => result.status === 'fulfilled')
        .length
      const totalCount = results.length

      console.log(`数据加载完成: ${successCount}/${totalCount} 个请求成功`)

      // 只有在至少有一个请求成功时才标记为已加载
      if (successCount > 0) {
        allDataLoaded.value = true
        console.log('所有数据列表加载完成')
      } else {
        console.warn('所有数据加载请求都失败了')
        // 不设置allDataLoaded为true，允许下次重试
      }
    } catch (error: any) {
      console.error('加载数据列表失败:', error)
      // 发生错误时不设置allDataLoaded为true，允许下次重试
      if (error.message === '数据加载超时') {
        ElMessage.error('数据加载超时，请稍后重试')
      }
    } finally {
      loadAllDataLoading.value = false
    }
  }

  // 监听抽屉状态变化
  watch(visible, newVisible => {
    if (newVisible) {
      // 抽屉打开时加载数据
      console.log('抽屉打开，加载数据...')
      
      // 只有在需要时才加载数据，避免重复加载
      if (!allDataLoaded.value) {
        // 延迟100ms执行，避免与其他监听器冲突
        setTimeout(() => {
          loadAllData()
        }, 100)
      }

      if (props.traceId && props.mode !== 'add') {
        loadTraceDetail(props.traceId)
      }
    } else {
      // 抽屉关闭时重置表单和数据加载标志
      console.log('抽屉关闭，重置表单')
      resetForm()
      
      // 重置全局数据加载标志，为下次打开做准备
      allDataLoaded.value = false
    }
  })

  // 监听客户ID变化 - 优化版本，避免死循环
  watch(
    () => props.customerId,
    (newCustomerId, oldCustomerId) => {
      if (newCustomerId && newCustomerId !== oldCustomerId && visible.value) {
        console.log('客户ID变化，重新加载数据...')
        
        // 只有在抽屉可见且数据需要更新时才重新加载
        if (formData.customer_id !== newCustomerId.toString()) {
          // 清除现有数据，重新加载
          contactList.value = []
          chanceList.value = []
          allDataLoaded.value = false
          
          // 延迟200ms执行，避免与visible监听器冲突
          setTimeout(() => {
            if (visible.value && !allDataLoaded.value) {
              loadAllData()
            }
          }, 200)
        }
      }
    }
  )

  // 监听traceId变化，加载详情 - 只在编辑/查看模式下触发
  watch(
    () => props.traceId,
    (newVal, oldVal) => {
      if (newVal && newVal !== oldVal && (props.mode === 'edit' || props.mode === 'view')) {
        loadTraceDetail(newVal)
      }
    }
  )

  // 监听mode变化，重置表单 - 只在模式真正变化时触发
  watch(
    () => props.mode,
    (newMode, oldMode) => {
      if (newMode !== oldMode) {
        resetForm()
      }
    }
  )

  // 监听customerId变化，更新表单数据 - 优化版本
  watch(
    () => props.customerId,
    (newVal, oldVal) => {
      if (newVal && newVal !== oldVal && newVal.toString() !== formData.customer_id) {
        formData.customer_id = newVal.toString()
        // 只有在需要时才清除缓存列表
        if (visible.value) {
          contactList.value = []
          chanceList.value = []
          allDataLoaded.value = false
        }
      }
    }
  )

  // 是否是查看模式
  const isView = computed(() => props.mode === 'view')

  // 抽屉标题
  const drawerTitle = computed(() => {
    switch (props.mode) {
      case 'add':
        return '新增客户跟进'
      case 'edit':
        return '编辑客户跟进'
      case 'view':
        return '查看客户跟进'
      default:
        return '客户跟进'
    }
  })

  // 监听traceId变化，加载详情
  watch(
    () => props.traceId,
    newVal => {
      if (newVal && (props.mode === 'edit' || props.mode === 'view')) {
        loadTraceDetail(newVal)
      }
    }
  )

  // 监听mode变化，重置表单
  watch(
    () => props.mode,
    () => {
      resetForm()
    }
  )

  // 监听customerId变化，更新表单数据
  watch(
    () => props.customerId,
    newVal => {
      if (newVal) {
        formData.customer_id = newVal.toString()
        // 清除联系人、机会线索列表缓存，为新客户加载
        contactList.value = []
        chanceList.value = []
      }
    }
  )

  // 加载跟进类型列表
  const loadTraceTypes = async () => {
    // 防止重复加载 - 使用缓存机制
    if (typesLoading.value || traceTypes.value.length > 0) {
      console.log('跟进类型列表已加载或正在加载，跳过请求')
      return
    }

    typesLoading.value = true
    let requestCompleted = false

    try {
      console.log('开始加载跟进类型列表...')

      const response: any = await request({
        url: '/api/customer/basic/set',
        method: 'get',
        params: { types: 4 }, // 跟进阶段类型
        timeout: 10000,
      })

      requestCompleted = true

      console.log('跟进类型列表响应:', response)

      if (response && response.code === 0) {
        traceTypes.value = response.data || []
        console.log('跟进类型列表加载成功，共', traceTypes.value.length, '条数据')
        console.log('跟进类型列表数据结构：', traceTypes.value.slice(0, 3)) // 只打印前3条数据用于调试
      } else {
        console.error('API返回错误:', response)
        ElMessage.error(response?.msg || '加载跟进类型列表失败')
      }
    } catch (error: any) {
      console.error('加载跟进类型列表失败:', error)

      if (!requestCompleted) {
        if (error.code === 'ERR_CANCELED') {
          console.log('跟进类型列表请求被取消，可能是重复请求，已忽略')
          return
        } else {
          ElMessage.error('加载跟进类型列表失败，请稍后重试')
        }
      }
    } finally {
      typesLoading.value = false
    }
  }

  // 加载联系人列表
  const loadContactList = async () => {
    if (!props.customerId) return

    // 防止重复加载 - 使用缓存机制
    if (contactLoading.value || contactList.value.length > 0) {
      console.log('联系人列表已加载或正在加载，跳过请求')
      return
    }

    contactLoading.value = true
    try {
      console.log('开始加载联系人列表...')

      const response: any = await request({
        url: '/api/customer/contact/list',
        method: 'get',
        params: {
          customer_id: props.customerId,
          page: 1,
          limit: 100,
        },
      })

      console.log('联系人列表响应:', response)

      if (response && response.code === 0) {
        contactList.value = response.data.list || []
        console.log('联系人列表加载成功，共', contactList.value.length, '条数据')
      } else {
        console.error('API返回错误:', response)
        ElMessage.error(response?.msg || '加载联系人列表失败')
      }
    } catch (error: any) {
      console.error('加载联系人列表失败:', error)

      // 对于ERR_CANCELED错误，不显示错误提示
      if (error.code === 'ERR_CANCELED') {
        console.log('联系人列表请求被取消，可能是重复请求，已忽略')
      } else {
        ElMessage.error('加载联系人列表失败，请稍后重试')
      }
    } finally {
      contactLoading.value = false
    }
  }

  // 加载机会线索列表
  const loadChanceList = async () => {
    if (!props.customerId) return

    // 防止重复加载 - 使用缓存机制
    if (chanceLoading.value || chanceList.value.length > 0) {
      console.log('机会线索列表已加载或正在加载，跳过请求')
      return
    }

    chanceLoading.value = true
    try {
      console.log('开始加载机会线索列表...')

      const response: any = await request({
        url: '/api/customer/chance/list',
        method: 'get',
        params: {
          customer_id: props.customerId,
          page: 1,
          limit: 100,
        },
      })

      console.log('机会线索列表响应:', response)

      if (response && response.code === 0) {
        chanceList.value = response.data.list || []
        console.log('机会线索列表加载成功，共', chanceList.value.length, '条数据')
      } else {
        console.error('API返回错误:', response)
        ElMessage.error(response?.msg || '加载机会线索列表失败')
      }
    } catch (error: any) {
      console.error('加载机会线索列表失败:', error)

      // 对于ERR_CANCELED错误，不显示错误提示
      if (error.code === 'ERR_CANCELED') {
        console.log('机会线索列表请求被取消，可能是重复请求，已忽略')
      } else {
        ElMessage.error('加载机会线索列表失败，请稍后重试')
      }
    } finally {
      chanceLoading.value = false
    }
  }

  // 跟进阶段列表复用跟进类型数据，避免重复请求
  const loadStageList = async () => {
    // 直接复用traceTypes数据，不发起新请求
    stageLoading.value = true

    try {
      console.log('跟进阶段列表复用跟进类型数据...')

      // 等待traceTypes数据加载完成
      let retryCount = 0
      while (traceTypes.value.length === 0 && retryCount < 20) {
        await new Promise(resolve => setTimeout(resolve, 50))
        retryCount++
      }

      if (traceTypes.value.length > 0) {
        // 复用traceTypes数据
        stageList.value = traceTypes.value.map((item: any) => ({
          ...item,
          cachedAt: Date.now(),
        }))
        console.log('跟进阶段列表复用成功，共', stageList.value.length, '条数据')
        console.log('跟进阶段列表数据结构：', stageList.value.slice(0, 3))

        // 详细检查字段映射
        if (stageList.value.length > 0) {
          const firstItem = stageList.value[0]
          console.log('第一个选项完整数据：', firstItem)
          console.log('title字段：', firstItem.title)
          console.log('name字段：', firstItem.name)
          console.log('label字段：', firstItem.label)
          console.log('字段映射结果：', firstItem.title || firstItem.name || firstItem.label)
          console.log(
            '显示值：',
            firstItem.title || firstItem.name || firstItem.label || '未找到可用字段'
          )
        }
      } else {
        console.warn('跟进类型数据未就绪，等待后重试')
        // 如果traceTypes还没有数据，延迟100ms后重试
        setTimeout(() => {
          if (traceTypes.value.length > 0) {
            stageList.value = traceTypes.value.map((item: any) => ({
              ...item,
              cachedAt: Date.now(),
            }))
            console.log('延迟加载跟进阶段列表成功，共', stageList.value.length, '条数据')
          }
          stageLoading.value = false
        }, 100)
        return
      }
    } catch (error: any) {
      console.error('跟进阶段列表复用失败:', error)
    } finally {
      stageLoading.value = false
    }
  }

  // 加载跟进记录详情
  const loadTraceDetail = async (traceId: string | number) => {
    try {
      // 使用any类型来避免类型错误
      const response: any = await request({
        url: '/api/customer/trace/view',
        method: 'get',
        params: { id: traceId },
      })

      console.log('获取跟进记录响应:', response) // 添加日志，帮助调试

      if (response && response.code === 0 && response.data) {
        // 填充表单数据
        formData.id = response.data.id
        formData.customer_id = response.data.cid
        formData.content = response.data.content

        // 将时间戳转换为日期字符串
        const followTime = Number(response.data.follow_time)
        const nextTime = Number(response.data.next_time)

        if (followTime) {
          const followDate = new Date(followTime * 1000) // 秒转毫秒
          const year = followDate.getFullYear()
          const month = String(followDate.getMonth() + 1).padStart(2, '0')
          const day = String(followDate.getDate()).padStart(2, '0')
          const hour = String(followDate.getHours()).padStart(2, '0')
          const minute = String(followDate.getMinutes()).padStart(2, '0')
          const second = String(followDate.getSeconds()).padStart(2, '0')
          formData.follow_time = `${year}-${month}-${day} ${hour}:${minute}:${second}`
        } else {
          formData.follow_time = ''
        }

        if (nextTime) {
          const nextDate = new Date(nextTime * 1000) // 秒转毫秒
          const year = nextDate.getFullYear()
          const month = String(nextDate.getMonth() + 1).padStart(2, '0')
          const day = String(nextDate.getDate()).padStart(2, '0')
          const hour = String(nextDate.getHours()).padStart(2, '0')
          const minute = String(nextDate.getMinutes()).padStart(2, '0')
          const second = String(nextDate.getSeconds()).padStart(2, '0')
          formData.next_time = `${year}-${month}-${day} ${hour}:${minute}:${second}`
        } else {
          formData.next_time = ''
        }

        formData.admin_id = response.data.admin_id
        formData.admin_name = response.data.admin_name
        formData.create_time = response.data.create_time

        // 设置新的字段数据
        formData.types = response.data.types ? response.data.types.toString() : ''
        formData.contact_id = response.data.contact_id ? response.data.contact_id.toString() : ''
        formData.chance_id = response.data.chance_id ? response.data.chance_id.toString() : ''
        formData.stage = response.data.stage ? response.data.stage.toString() : ''

        console.log('加载的数据:', formData) // 添加日志，帮助调试
      } else {
        ElMessage.error(response?.msg || '获取跟进记录详情失败')
        closeDrawer()
      }
    } catch (error) {
      console.error('获取跟进记录详情失败:', error)
      ElMessage.error('获取跟进记录详情失败')
      closeDrawer()
    }
  }

  // 处理确认事件
  const handleConfirm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async valid => {
      if (!valid) return

      submitting.value = true

      try {
        // 将日期字符串转换为秒级时间戳并确保是整数
        let followTimeStamp = 0
        let nextTimeStamp = 0

        if (formData.follow_time) {
          const followDate = new Date(formData.follow_time)
          followTimeStamp = Math.round(followDate.getTime() / 1000)
        }

        if (formData.next_time) {
          const nextDate = new Date(formData.next_time)
          nextTimeStamp = Math.round(nextDate.getTime() / 1000)
        }

        // 转换时间戳格式，确保发送到后端的是秒级时间戳
        const submitData: any = {
          customer_id: props.customerId,
          content: formData.content,
          follow_time: formData.follow_time,
          next_time: formData.next_time || null,
          types: formData.types || '',
          contact_id: formData.contact_id || '',
          chance_id: formData.chance_id || '',
          stage: formData.stage || '',
          // 如果有跟进ID则更新，否则新增
          id: props.traceId || null,
        }

        // 编辑模式需要添加id
        if (props.mode === 'edit') {
          submitData.id = formData.id

          // 使用customerApi.editCustomerTrace
          try {
            const response: any = await customerApi.editCustomerTrace(submitData)

            if (response && response.code === 0) {
              ElMessage.success('编辑跟进记录成功')
              emit('success')
              closeDrawer()
            } else {
              ElMessage.error(response?.msg || '编辑跟进记录失败')
            }
          } catch (error) {
            ElMessage.error('编辑跟进记录失败')
          }
        } else {
          // 新增模式 - 使用customerApi.addCustomerTrace
          try {
            const response: any = await customerApi.addCustomerTrace(submitData)

            if (response && response.code === 0) {
              ElMessage.success('添加跟进记录成功')
              emit('success')
              closeDrawer()
            } else {
              ElMessage.error(response?.msg || '添加跟进记录失败')
            }
          } catch (error) {
            ElMessage.error('添加跟进记录失败')
          }
        }
      } catch (error) {
        ElMessage.error(props.mode === 'add' ? '添加失败' : '编辑失败')
      } finally {
        submitting.value = false
      }
    })
  }

  // 处理next_time清除事件
  const handleNextTimeClear = () => {
    formData.next_time = '' // 设置为空字符串而不是null
  }

  // 关闭抽屉前的处理
  const handleBeforeClose = async () => {
    if (props.mode === 'view') {
      return true
    }

    // 检查表单是否有改动
    if (formData.content) {
      try {
        await ElMessageBox.confirm('确定要关闭吗？未保存的内容将会丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        return true
      } catch {
        // 用户取消关闭
        return false
      }
    } else {
      return true
    }
  }

  // 关闭抽屉
  const closeDrawer = () => {
    visible.value = false
  }

  // 初始化
  onMounted(() => {
    resetForm()
  })
</script>

<style scoped>
  .trace-form {
    padding: 20px;
  }

  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    padding: 0 20px 20px;
  }

  .trace-info {
    background-color: #f8f9fa;
    padding: 10px 15px;
    border-radius: 4px;
    margin-top: 10px;
  }

  .info-item {
    display: flex;
    margin-bottom: 8px;
  }

  .info-item .label {
    font-weight: 500;
    color: #606266;
    width: 90px;
  }

  .info-item .value {
    color: #303133;
    flex: 1;
  }
</style>



